<?php
/**
 * 飞信机器人--功能插件--彩铃模块
 * 功能：实现彩铃搜索、订阅（此功能需要IP授权，请联系 “结信网络技术服务（上海）有限公司”）
 * 数据表：无
 * 作者： Kelvin
 * 联系： msn:shichangguo@msn.com, qq:191848423
*/
class CaiLing extends CommonPlugin
{
	var $UUID='1b71bf66-5886-433f-a76f-9adf1d3dd045';
	var $pageSize=6;

	public function CaiLing(&$session, $pid, $extraPara="")
	{
		parent::__construct($session, $pid, $extraPara);
	}
	
	public function getPage()
	{
		$page = $this->session->getValue("{$this->UUID}_page");
		if($page==0)$page=1;
		return $page;
	}
	public function setPage($page)
	{
		$this->session->set("{$this->UUID}_page", $page);
	}
	public function getKeyword()
	{
		$key = $this->session->getStr("{$this->UUID}_key");
		return $key;
	}
	public function setKeyword($key)
	{
		$this->session->set("{$this->UUID}_key", $key);
	}	
	public function setList($list)
	{
		$listEncode = base64_encode( serialize($list));
		$this->session->set("CaiLing_list", $listEncode);
	}
	
	public function getList()
	{
		$v = $this->session->getStr("CaiLing_list");
		if( $v == "") return array();
		
		return unserialize(base64_decode($v));
	}
	
	private function subAction($song)
	{
		$mobile = $this->session->buddyArray['mobile'];
		
		if(empty($mobile))
		{
			return "请公开您的手机号码（点选机器人，右键-公开手机号码）！".$this->getFooter(',l-返回列表');
		}
		
		$serial = $song[2];
		/*echo "===================\n";
		echo $serial."\n";		
		echo $mobile."\n";
		echo "===================\n";*/
		
		$request = xmlrpc_encode_request("MineGateway.orderCRBTV2", array("521101",$mobile, $serial));
		$context = stream_context_create(array('http' => array(
		    'method' => "POST",
		    'header' => "Content-Type: text/xml",
		    'content' => $request
		)));
		$file = file_get_contents("http://211.137.86.69:80/xmlrpc", false, $context);
		$response = xmlrpc_decode($file);
		if (xmlrpc_is_fault($response))
		{
		    return "xmlrpc: $response[faultString] ($response[faultCode])";
		}

		if( $response['0'] == '000000' )
		{
			return "订阅成功，订制请求已发送，请留意系统下发的短信。\n". $this->getFooter(',l-返回列表  p--上一页 n--下一页');
		}else 
		{
			//return "订阅失败：{$response['0']}". $this->getFooter(',l-返回列表');
			return "订阅失败,请稍后重试！\n". $this->getFooter(',l-返回列表 p--上一页 n--下一页');
		}
	}
	private function subSong($input)
	{
		$list = $this->getList();
		$count = count($list);
		
		if( $input>$count && $input<1 )
		{
			return "输入错误(范围不正确\n".$this->getFooter();
		}
		for($i=0; $i<$count; $i++)
		{
			if( ($i+1) == $input )
			{
				return $this->subAction($list[$i]);
			}
		}
	}
	
	function getListFromCache()
	{
		$list = $this->getList();
		$msg = "<Font Face='楷体' Color='-16744320' Size='10.5'>";
		for($i=0; $i<count($list); $i++)
		{
			$msg.="[".($i+1)."]". $list[$i][0];
			$msg.= "(".$list[$i][1]." ".$list[$i][3]."元)";
			$msg.= "\n";
		}
	    $msg.="</font>";
	    $msg.=$this->getFooter(' 数字--订阅  p--上一页 n--下一页 输入查询内容-新的搜索');
	    
	    return $msg;
	}
	
	private function getSongList($str)
	{
		$mobile = $this->session->buddyArray['mobile'];
		if(empty($mobile))
		{
			return "请公开您的手机号码（点选机器人，右键-公开手机号码）！".$this->getFooter(',l-返回列表');
		}
	
		$strEncode = $str;

		$output_options = array(
              	"output_type" => "xml",
              	"verbosity" => "pretty",
              	"escaping" => array("markup"),
              	"version" => "xmlrpc",
              	"encoding" => "utf-8"
              	);

        $page = $this->getPage();
        $start = ($page-1)*$this->pageSize+1;
		$request = xmlrpc_encode_request("MineGateway.musicSearchV2", array("521101","{$strEncode}","{$mobile}","{$start}","{$this->pageSize}"),$output_options);
		$context = stream_context_create(array('http' => array(
		    'method' => "POST",
		    'header' => "Content-Type: text/xml",
		    'content' => $request
		)));
		$file = file_get_contents("http://211.137.86.69:80/xmlrpc", false, $context);
		$response = xmlrpc_decode($file);
		if (xmlrpc_is_fault($response))
		{
		    return "xmlrpc: $response[faultString] ($response[faultCode])";
		} else
		{
			$msg = "<Font Face='楷体' Color='-16744320' Size='10.5'>";
			$msg.= "您要搜索的内容：$str(第 {$page} 页)\n\n";
			$retCode = $response[0];
			if( $retCode != "000000" && $retCode != "000001")
			{
				return "搜索错误，请继续输入查询</font>\n".$this->getFooter();
			}
			
			if( !empty($response[1]))
				$msg .= $response[1]."\n";
			
			$count = count($response[2]);
			if( $count>0 )
			{
				for($i=0; $i<$count; $i++)
				{
					$msg.="[".($i+1)."]". $response[2][$i][0];
					$msg.= "(".$response[2][$i][1]." ".$response[2][$i][3]."元)";
					$msg.= "\n";
				}
			}else
			{
				$msg.="搜索无结果！";
			}
		    // $msg.="\n".$response[3]."\n";
		    $msg.="\n感谢使用10658830进行搜索，直接输入数字序号下载该彩铃，稍后您将收到一条确认短信，请按短信提示进行操作，即可完成下载!\n";
		    $msg.="</font>";
		    
		    if($page == 1 && $count>0 )
		    {
		    	$msg.=$this->getFooter(' 数字--订阅 n--下一页  输入查询内容-新的搜索');
		    }else if($page > 1 && $count>0 )
		    {
		    	$msg.=$this->getFooter(' 数字--订阅 p--上一页 n--下一页  输入查询内容-新的搜索');
		    }else if($page > 1 && $count==0)
		    {
		    	$msg.=$this->getFooter(' 数字--订阅 p--上一页  输入查询内容-新的搜索');
		    }
		    
		    $this->setList($response[2]);
	
		    return $msg;
		}
	}
	
	public function getTips()
	{
		$action = $this->extraParam['action'];
		return "欢迎使用飞信彩铃业务，输入您要查询的歌曲或者歌手名，例如‘蔡依林’、‘爱得起’\n".$this->getFooter();		
	}
	
	public function handle($input)
	{
		if( parent::handleInput($input)) return false;
		
		if( is_numeric($input))
		{
			return $this->subSong(intval($input));
		}if($input == 'l')
		{
			return $this->getListFromCache();
		}else if($input == 'p')
		{
			$page = $this->getPage();
			$page--;
			if( $page==0 )$page=1;
			
			$this->setPage($page);
			$key = $this->getKeyword();
			return $this->getSongList($key);
		}else if($input == 'n')
		{
			$page = $this->getPage();
			$page++;
			$this->setPage($page);
			$key = $this->getKeyword();
			return $this->getSongList($key);
		}else
		{
			$this->setPage(1);
			$this->setKeyword($input);
			return $this->getSongList($input);
		}
	}
}

?>
